package com.rpc.core.holder.rag;

import com.rpc.core.register.impl.ZkRegister;
import com.rpc.core.remoting.Client;
import com.rpc.core.remoting.impl.NettyClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

public class RegInfoEnhancer {
    private Logger logger = LoggerFactory.getLogger(RegInfoEnhancer.class);
    private RegInfo info;

    private volatile Client client;

    private ApplicationContext context;

    public RegInfoEnhancer(RegInfo info, ApplicationContext context) {
        this.info = info;
        this.context = context;
    }

    public RegInfo getInfo() {
        return info;
    }

    public void setInfo(RegInfo info) {
        this.info = info;
    }

    public Client getClient() {
        if(client!=null){
            return client;
        }
        synchronized (this){
            if(client!=null){
                return client;
            }
            this.client=createClient();
        }

        return client;
    }

    private NettyClient createClient() {

        NettyClient nettyClient = new NettyClient(context,this);

        String address = info.getAddress();
        String[] split = address.split(":");
        try {
            nettyClient.start(split[0], Integer.parseInt(split[1]));
        } catch (Exception e) {
            logger.info("{} create client fail",e.getMessage());
            return null;
        }
        return nettyClient;
    }

    public void close(){
        if (this.client!=null) {
            client.stop();
        }
    }

    public void deleteClient() {
        this.client=null;
    }
}
